package servlet;

import entity.Page;
import entity.Record;
import service.LendService;
import service.impl.LendServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "RecordsCountByPageServlet", value = "/RecordsCountByPageServlet")
public class RecordsCountByPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String currentPage=request.getParameter("currentPage");
        String search=request.getParameter("search_2");
        LendService lendService=new LendServiceImpl();
        Page page=new Page();
        currentPage=(currentPage==null?"0":currentPage);
        page.setCurrentPage(Integer.parseInt(currentPage));
        if(search==null||"null".equals(search)){
            String sql="select count(*) from record_count";
            int count=lendService.getTotalCount(sql,null);
            page.setTotalCount(count);
            page.setPageSize(10);
            List<Record> records=lendService.queryCountByPage(page.getCurrentPage(),page.getPageSize());
            page.setRecord(records);
            request.setAttribute("page",page);
            request.getSession().setAttribute("search_2",search);
            request.getRequestDispatcher("recordsCou.jsp").forward(request,response);
        }else{
            String sql="select count(*) from record_count where bookId=?";
            Object[] params={search};
            int count=lendService.getTotalCount(sql,params);
            page.setTotalCount(count);
            page.setPageSize(10);
            List<Record> records=lendService.queryCountByPageRequire(page.getCurrentPage(), page.getPageSize(), search);
            page.setRecord(records);
            request.setAttribute("page",page);
            request.getSession().setAttribute("search_2",search);
            request.getRequestDispatcher("recordsCou.jsp").forward(request,response);
        }
    }
}
